<?php
/**
 * 首屏广告
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/6/3
 * @copyright PanxSoft Inc.
 */
namespace App\Http\Controllers\Admin\V1;


use App\Http\Controllers\ApiController;
use App\Http\Middleware\LocaleEnv;
use App\Http\Requests\Admin\V1\BulletinBoard\BulletinBoardStoreRequest;
use App\Http\Requests\Admin\V1\BulletinBoard\BulletinBoardUpdateRequest;
use App\Models\BulletinBoard;
use App\Services\Utils\TimeHelper;
use Illuminate\Http\Request;

class BulletinBoardController extends ApiController
{
    const ROUTES = [
        'index'   => 'admin.v1.BulletinBoard.index',
        'store'   => 'admin.v1.BulletinBoard.store',
        'update'  => 'admin.v1.BulletinBoard.update',
        'destroy' => 'admin.v1.BulletinBoard.destroy',
    ];

    public function index()
    {
        $bulletin_boards = (new BulletinBoard)
            ->oldest('sort_order')
            ->latest('created_at')
            ->paginate(\request()->get('per_page') ?: 15);

        return $this->response(compact('bulletin_boards'));
    }

    public function store(BulletinBoardStoreRequest $request)
    {
        $bulletin_board = (new BulletinBoard)->create($this->assembleStoreData($request));

        return $this->response(compact('bulletin_board'));
    }

    /**
     * @param BulletinBoardUpdateRequest $request
     * @param $key
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function update(BulletinBoardUpdateRequest $request, $key)
    {
        $bulletin_board = (new BulletinBoard)->find($key);
            $this->checkItemExist($bulletin_board, trans('checker.admin.bulletin_board'));

        $updated = $bulletin_board->update($this->assembleStoreData($request));

        return $this->response(compact('bulletin_board', 'updated'));
    }

    public function destroy($key)
    {
        $deleted = (new BulletinBoard)->destroy($key);

        return $this->response(compact('deleted'));
    }

    /**
     * @param Request $request
     *
     * @return array
     */
    private function assembleStoreData(Request $request): array
    {
        $data = $request->only(['name', 'title', 'content', 'started_at', 'ended_at', 'sort_order']);

        // admin panel request timezone convert to UTC time
        $tz_offset = LocaleEnv::timezoneOffset();
        $data['started_at'] = TimeHelper::offsetMinutes($data['started_at'], $tz_offset);
        $data['ended_at'] = TimeHelper::offsetMinutes($data['ended_at'], $tz_offset);

        return $data;
}
}